<?php

namespace Ivr\HttpBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

class Vcc8013051003Controller extends Controller
{
    private $messages = array(
        '1441' => '尊敬的客户您好，为节省您的宝贵时间，您可通过关注天尧平安银行微信公众号进行咨询，微信号码ty-pingan',
        '1406' => '尊敬的客户您好，为节省您的宝贵时间，您可通过关注天尧广发银行微信公众号进行咨询，微信号码ty-cgb',
        '1278' => '尊敬的客户您好，为节省您的宝贵时间，您可通过关注天尧中信银行微信公众号进行咨询，微信号码ty-zxyh',
        '437' => '尊敬的客户您好，为节省您的宝贵时间，您可通过关注我司微信公众号进行咨询，我司微信公众号tygroup',
        '1442' => '尊敬的客户您好，为节省您的宝贵时间，您可通过关注天尧浦发银行微信公众号进行咨询，微信号码ty_spd'
    );

    private $signature = '北京天尧';

    public function indexAction($ivr_id)
    {
        $caller = $this->get('request')->get('caller');
        $params = array(
            'vcc_id' => 142,
            'vcc_code' => '8013051003',
            'ag_id' => '8984',
            'receiver_phone' => $caller,
            'sms_contents' => isset($this->messages[$ivr_id]) ? $this->messages[$ivr_id] : '',
            'client_sms_id' => 1,
            'signature' => $this->signature,
            'token' => '5c8d6d964020f948d243e4a311749c6e',
            'flag' => '0',
        );

        $logger = $this->get('logger');
        $url = $this->get('service_container')->getParameter('wintelapi_sms');
        $logger->info(sprintf('发起发送短信请求到 %s, 参数为【%s】.', $url, json_encode($params)));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url.'/sms/send');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $response = curl_exec($ch);
        $responseArray = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $logger->error(sprintf('响应结果为非json格式，结果为【%s】.', $response));

            return new JsonResponse(array(
                'result' => 'failure'
            ));
        }

        $code = isset($responseArray['code']) ? $responseArray['code'] : 0;
        $message = isset($responseArray['message']) ? $responseArray['message'] : '';
        if ($code == 200) {
            $logger->info(sprintf('发送短信成功，结果为 %s.', $message));

            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'code' => $code
                )
            ));
        } else {
            $logger->error(sprintf('发送短信失败，结果为 %s.', $message));

            return new JsonResponse(array(
                'result' => 'failure'
            ));
        }
    }
}
